import hashlib

from django_redis import get_redis_connection

from md_sc.config import REDIS_KEY_MAP, QINIU_DOMAIN
from celery_tasks.email.config import EMAIL_VERIFY_URL


class UsernameConverter:
    """自定义路由转换器去匹配用户名"""
    # 定义匹配用户名的正则表达式
    regex = '[a-zA-Z0-9_-]{5,20}'

    def to_python(self, value):
        return str(value)

    def to_url(self, value):
        return str(value)


def redis_check_sms_code(mobile, code):
    redis_conn = get_redis_connection('verify_code')
    r_code = redis_conn.get(REDIS_KEY_MAP.get('SmsCode') + mobile).decode()
    if code == r_code:
        redis_conn.delete(REDIS_KEY_MAP.get('SmsCode') + mobile)
        return True


def get_email_url(uid, email):
    hl = hashlib.md5()
    hl.update((str(uid) + email).encode(encoding='utf-8'))

    return EMAIL_VERIFY_URL + hl.hexdigest(), hl.hexdigest()
